// 认证相关工具函数
import userStore from '@/store/user.js'

// 获取用户ID
export const getUserId = () => {
  // 尝试多种方式获取用户ID
  let userId = uni.getStorageSync('userId')
  if (!userId) {
    // 从userInfo中获取
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo && userInfo.userId) {
      userId = userInfo.userId
    }
  }
  return userId
}

// 获取用户信息
export const getUserInfo = () => {
  return uni.getStorageSync('userInfo') || {}
}

// 检查是否已登录 - 直接检查本地存储，不依赖store
export const isLoggedIn = () => {
  const token = uni.getStorageSync('token')
  return !!token
}

// 获取token
export const getToken = () => {
  return uni.getStorageSync('token') || ''
}

// 设置用户信息
export const setUserInfo = (userInfo) => {
  // 确保包含userId
  if (userInfo && (userInfo.userId || userInfo.id)) {
    const normalizedUserInfo = {
      userId: userInfo.userId || userInfo.id,
      nickName: userInfo.nickName || userInfo.userName,
      userName: userInfo.userName,
      avatar: userInfo.avatar,
      email: userInfo.email,
      phonenumber: userInfo.phonenumber,
      sex: userInfo.sex,
      remark: userInfo.remark
    }
    
    // 保存到本地存储
    uni.setStorageSync('userInfo', normalizedUserInfo)
    
    // 同时保存userId到根级别，方便访问
    if (normalizedUserInfo.userId) {
      uni.setStorageSync('userId', normalizedUserInfo.userId)
    }
    
    return normalizedUserInfo
  }
  return null
}

// 清除用户信息
export const clearUserInfo = () => {
  uni.removeStorageSync('userInfo')
  uni.removeStorageSync('userId')
  uni.removeStorageSync('token')
}

// 检查并跳转登录
export const checkAndRedirectToLogin = (message = '请先登录') => {

  
  // 检查token - 直接检查本地存储
  const token = uni.getStorageSync('token')
  
  
  if (!token) {
    
    uni.showToast({ title: message, icon: 'none' })
    setTimeout(() => {
      uni.reLaunch({ url: '/pages/login' })
    }, 1500)
    return false
  }
  
  // 检查用户ID
  const userId = getUserId()

  
  if (!userId) {
    
    uni.showToast({ title: '用户信息不完整，请重新登录', icon: 'none' })
    clearUserInfo()
    setTimeout(() => {
      uni.reLaunch({ url: '/pages/login' })
    }, 1500)
    return false
  }

  return true
}